<template>
  <div class="log-history">
    <div class="page-header">
      <h2>历史日志</h2>
      <p>查看系统操作记录和活动历史</p>
    </div>

    <!-- 日志统计卡片 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6" v-for="stat in logStats" :key="stat.id">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon :size="32">
                <component :is="stat.icon" />
              </el-icon>
            </div>
            <div class="stat-content">
              <h3>{{ stat.value }}</h3>
              <p>{{ stat.label }}</p>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 日志标签页 -->
    <div class="logs-section">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>日志详情</span>
            <div class="header-actions">
              <el-button type="primary" @click="refreshLogs" :icon="Refresh">
                刷新
              </el-button>
              <el-dropdown @command="handleExport">
                <el-button :icon="Download">
                  导出<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="excel">导出Excel</el-dropdown-item>
                    <el-dropdown-item command="pdf">导出PDF</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </template>
        
        <!-- 筛选条件 -->
        <div class="filter-section">
          <el-form :model="queryParams" inline>
            <el-form-item label="用户名">
              <el-input v-model="queryParams.username" placeholder="请输入用户名" clearable />
            </el-form-item>
            <el-form-item label="日志类型">
              <el-select v-model="queryParams.logType" placeholder="请选择日志类型" clearable>
                <el-option label="登录日志" value="LOGIN" />
                <el-option label="操作日志" value="OPERATION" />
                <el-option label="数据日志" value="DATA" />
                <el-option label="错误日志" value="ERROR" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <el-option label="成功" value="SUCCESS" />
                <el-option label="失败" value="FAILED" />
              </el-select>
            </el-form-item>
            <el-form-item label="时间范围">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                @change="handleDateRangeChange"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        
        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
          <!-- 操作日志 -->
          <el-tab-pane label="操作日志" name="operation">
            <el-table :data="operationLogs" style="width: 100%" stripe v-loading="loading">
              <el-table-column label="时间" width="180">
                <template #default="scope">
                  {{ formatTime(scope.row.createTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="action" label="操作" width="120" />
              <el-table-column prop="description" label="描述" />
              <el-table-column prop="ipAddress" label="IP地址" width="140" />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.status === 'SUCCESS' ? 'success' : 'danger'">
                    {{ scope.row.status === 'SUCCESS' ? '成功' : '失败' }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <!-- 登录日志 -->
          <el-tab-pane label="登录日志" name="login">
            <el-table :data="loginLogs" style="width: 100%" stripe v-loading="loading">
              <el-table-column label="时间" width="180">
                <template #default="scope">
                  {{ formatTime(scope.row.createTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="ipAddress" label="IP地址" width="140" />
              <el-table-column prop="userAgent" label="设备" width="200" />
              <el-table-column prop="description" label="描述" width="150" />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.status === 'SUCCESS' ? 'success' : 'danger'">
                    {{ scope.row.status === 'SUCCESS' ? '成功' : '失败' }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <!-- 系统日志 -->
          <el-tab-pane label="系统日志" name="system">
            <el-table :data="systemLogs" style="width: 100%" stripe v-loading="loading">
              <el-table-column label="时间" width="180">
                <template #default="scope">
                  {{ formatTime(scope.row.createTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="logType" label="级别" width="100">
                <template #default="scope">
                  <el-tag :type="getLogLevelType(scope.row.logType)">
                    {{ scope.row.logType }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="action" label="操作" width="150" />
              <el-table-column prop="description" label="消息" />
            </el-table>
          </el-tab-pane>

          <!-- 安全日志 -->
          <el-tab-pane label="安全日志" name="security">
            <el-table :data="securityLogs" style="width: 100%" stripe v-loading="loading">
              <el-table-column label="时间" width="180">
                <template #default="scope">
                  {{ formatTime(scope.row.createTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="action" label="事件" width="150" />
              <el-table-column prop="description" label="描述" />
              <el-table-column prop="ipAddress" label="IP地址" width="140" />
              <el-table-column prop="status" label="状态" width="120">
                <template #default="scope">
                  <el-tag :type="scope.row.status === 'SUCCESS' ? 'success' : 'danger'">
                    {{ scope.row.status === 'SUCCESS' ? '成功' : '失败' }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
        
        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="queryParams.page"
            v-model:page-size="queryParams.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, Download, ArrowDown } from '@element-plus/icons-vue'
import { getLogsByPage, getTodayStats, exportLogs, exportLogsPDF } from '@/api/log'

export default {
  name: 'LogHistory',
  components: {
    Refresh,
    Download,
    ArrowDown
  },
  setup() {
    const activeTab = ref('operation')
    const loading = ref(false)
    const dateRange = ref([])
    
    // 查询参数
    const queryParams = reactive({
      page: 1,
      size: 10,
      username: '',
      logType: '',
      status: '',
      startDate: '',
      endDate: ''
    })
    
    // 分页数据
    const pagination = reactive({
      total: 0,
      currentPage: 1,
      pageSize: 10
    })

    // 日志数据
    const operationLogs = ref([])
    const loginLogs = ref([])
    const systemLogs = ref([])
    const securityLogs = ref([])

    // 日志统计
    const logStats = ref([
      {
        id: 1,
        label: '今日操作',
        value: '0',
        icon: 'Document'
      },
      {
        id: 2,
        label: '登录次数',
        value: '0',
        icon: 'Monitor'
      },
      {
        id: 3,
        label: '安全事件',
        value: '0',
        icon: 'Warning'
      },
      {
        id: 4,
        label: '系统错误',
        value: '0',
        icon: 'DataAnalysis'
      }
    ])

    // 获取今日统计
    const fetchTodayStats = async () => {
      try {
        const response = await getTodayStats()
        if (response.code === 200) {
          const stats = response.data
          logStats.value[0].value = stats.total || '0'
          logStats.value[1].value = stats.loginCount || '0'
          logStats.value[2].value = stats.failedCount || '0'
          logStats.value[3].value = stats.errorCount || '0'
        } else if (response.code === 403) {
          // 权限不足，显示默认值
          logStats.value[0].value = '0'
          logStats.value[1].value = '0'
          logStats.value[2].value = '0'
          logStats.value[3].value = '0'
        }
      } catch (error) {
        console.error('获取今日统计失败:', error)
        // 如果是权限不足，不显示错误消息
        if (error.response && error.response.status === 403) {
          logStats.value[0].value = '0'
          logStats.value[1].value = '0'
          logStats.value[2].value = '0'
          logStats.value[3].value = '0'
        }
      }
    }

    // 获取日志数据
    const fetchLogs = async () => {
      loading.value = true
      try {
        const params = {
          page: queryParams.page,
          size: queryParams.size,
          username: queryParams.username || undefined,
          logType: queryParams.logType || undefined,
          status: queryParams.status || undefined,
          startDate: queryParams.startDate || undefined,
          endDate: queryParams.endDate || undefined
        }
        
        const response = await getLogsByPage(params)
        if (response.code === 200) {
          const data = response.data
          const logs = data.records || []
          
          // 根据日志类型分类
          operationLogs.value = logs.filter(log => log.logType === 'OPERATION')
          loginLogs.value = logs.filter(log => log.logType === 'LOGIN')
          systemLogs.value = logs.filter(log => log.logType === 'ERROR')
          securityLogs.value = logs.filter(log => log.logType === 'DATA')
          
          // 更新分页信息
          pagination.total = data.total || 0
          pagination.currentPage = data.current || 1
          pagination.pageSize = data.size || 10
        } else if (response.code === 403) {
          // 权限不足，清空数据
          operationLogs.value = []
          loginLogs.value = []
          systemLogs.value = []
          securityLogs.value = []
          pagination.total = 0
          pagination.currentPage = 1
          pagination.pageSize = 10
        }
      } catch (error) {
        console.error('获取日志失败:', error)
        // 如果是权限不足，不显示错误消息
        if (error.response && error.response.status === 403) {
          operationLogs.value = []
          loginLogs.value = []
          systemLogs.value = []
          securityLogs.value = []
          pagination.total = 0
          pagination.currentPage = 1
          pagination.pageSize = 10
        } else {
          ElMessage.error('获取日志失败')
        }
      } finally {
        loading.value = false
      }
    }

    // 导出日志
    const handleExportLogs = async (type = 'excel') => {
      try {
        const params = {
          username: queryParams.username || undefined,
          logType: queryParams.logType || undefined,
          status: queryParams.status || undefined,
          startDate: queryParams.startDate || undefined,
          endDate: queryParams.endDate || undefined
        }
        
        let response, filename, mimeType
        if (type === 'pdf') {
          response = await exportLogsPDF(params)
          filename = `系统日志_${new Date().getTime()}.pdf`
          mimeType = 'application/pdf'
        } else {
          response = await exportLogs(params)
          filename = `系统日志_${new Date().getTime()}.xlsx`
          mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        }
        
        const blob = new Blob([response], { type: mimeType })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = filename
        link.click()
        window.URL.revokeObjectURL(url)
        ElMessage.success(`日志${type === 'pdf' ? 'PDF' : 'Excel'}导出成功`)
      } catch (error) {
        console.error('导出日志失败:', error)
        ElMessage.error('导出日志失败')
      }
    }

    // 处理导出命令
    const handleExport = (command) => {
      handleExportLogs(command)
    }

    const handleTabClick = (tab) => {
      ElMessage.info(`切换到${tab.props.label}`)
    }

    const refreshLogs = () => {
      fetchLogs()
      fetchTodayStats()
      ElMessage.success('日志已刷新')
    }

    // 处理日期范围变化
    const handleDateRangeChange = (dates) => {
      if (dates && dates.length === 2) {
        queryParams.startDate = dates[0]
        queryParams.endDate = dates[1]
      } else {
        queryParams.startDate = ''
        queryParams.endDate = ''
      }
    }

    // 搜索
    const handleSearch = () => {
      queryParams.page = 1
      fetchLogs()
    }

    // 重置
    const handleReset = () => {
      queryParams.username = ''
      queryParams.logType = ''
      queryParams.status = ''
      queryParams.startDate = ''
      queryParams.endDate = ''
      dateRange.value = []
      queryParams.page = 1
      fetchLogs()
    }

    // 分页大小变化
    const handleSizeChange = (size) => {
      queryParams.size = size
      queryParams.page = 1
      fetchLogs()
    }

    // 当前页变化
    const handleCurrentChange = (page) => {
      queryParams.page = page
      fetchLogs()
    }

    const getLogLevelType = (level) => {
      const types = {
        'INFO': 'info',
        'WARN': 'warning',
        'ERROR': 'danger',
        'DEBUG': 'success'
      }
      return types[level] || 'info'
    }

    const getSeverityType = (severity) => {
      const types = {
        '低': 'success',
        '中': 'warning',
        '高': 'danger'
      }
      return types[severity] || 'info'
    }

    // 格式化时间
    const formatTime = (time) => {
      if (!time) return ''
      return new Date(time).toLocaleString('zh-CN')
    }

    // 页面加载时获取数据
    onMounted(() => {
      fetchLogs()
      fetchTodayStats()
    })

    return {
      activeTab,
      operationLogs,
      loginLogs,
      systemLogs,
      securityLogs,
      logStats,
      loading,
      queryParams,
      pagination,
      dateRange,
      handleTabClick,
      refreshLogs,
      exportLogs: handleExportLogs,
      handleExport,
      handleDateRangeChange,
      handleSearch,
      handleReset,
      handleSizeChange,
      handleCurrentChange,
      getLogLevelType,
      getSeverityType,
      formatTime
    }
  }
}
</script>

<style scoped>
.log-history {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 30px;
  text-align: center;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: var(--text-color);
  font-size: 28px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: var(--text-color-secondary);
  font-size: 16px;
}

.stats-section {
  margin-bottom: 30px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  border: 1px solid #f0f0f0;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.stat-icon {
  color: var(--primary-color);
  background: rgba(24, 144, 255, 0.1);
  padding: 12px;
  border-radius: 8px;
}

.stat-content h3 {
  margin: 0 0 4px 0;
  font-size: 24px;
  font-weight: 600;
  color: var(--text-color);
}

.stat-content p {
  margin: 0;
  color: var(--text-color-secondary);
  font-size: 14px;
}

.logs-section {
  margin-bottom: 30px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.pagination-section {
  margin-top: 20px;
  text-align: center;
}

.card-header span {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-color);
}

.header-actions {
  display: flex;
  gap: 12px;
}

.el-table {
  margin-top: 16px;
}

.el-table .el-table__header {
  background: #fafbfc;
}

.el-table .el-table__row:hover {
  background: #f8f9fa;
}

@media (max-width: 768px) {
  .stats-section .el-col {
    margin-bottom: 16px;
  }
  
  .stat-card {
    padding: 20px;
  }
  
  .header-actions {
    flex-direction: column;
    gap: 8px;
  }
}
</style> 